<template>
  <div class="order-container">
    <div class="page-header">
      <h2>我的订单</h2>
    </div>
    
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部订单" name="ALL"></el-tab-pane>
      
      <el-tab-pane label="已支付" name="PAID"></el-tab-pane>
      <el-tab-pane label="已取消" name="CANCELLED"></el-tab-pane>
      <el-tab-pane label="已退款" name="REFUNDED"></el-tab-pane>
    </el-tabs>
    
    <div v-loading="loading">
      <div v-if="orders.length === 0" class="no-data">
        暂无订单数据
      </div>
      
      <el-card v-for="order in orders" :key="order.id" class="order-card">
        <div class="order-header">
          <div class="order-id">订单号: {{ order.id }}</div>
          <div class="order-status" :class="getStatusClass(order.status)">
            {{ getStatusText(order.status) }}
          </div>
        </div>
        
        <div class="order-content">
          <!-- 比赛信息 -->
          <div class="match-info">
            <div class="teams">
              <img :src="`http://localhost:8088/api/file/get/${getTeamLogo(order.matchId, 'home')}`" class="team-logo">
              <span class="vs">VS</span>
              <img :src="`http://localhost:8088/api/file/get/${getTeamLogo(order.matchId, 'away')}`" class="team-logo">
            </div>
            <div class="match-name">{{ getMatchName(order.matchId) }}</div>
            <div class="match-time">{{ getMatchTime(order.matchId) }}</div>
            <div class="venue-name">{{ getVenueName(order.matchId) }}</div>
          </div>
          
          <!-- 票务信息 -->
          <div class="ticket-info">
            <div class="section-name">{{ getSectionName(order.sectionId) }}</div>
            <div class="seat-number">座位号: {{ order.ticketNumber }}</div>
            <div class="contact-info">
              <p><i class="el-icon-user"></i> {{ order.name }}</p>
              <p><i class="el-icon-phone"></i> {{ order.phone }}</p>
              <p><i class="el-icon-message"></i> {{ order.email }}</p>
            </div>
            <div class="price">¥{{ order.totalAmount }}</div>
          </div>
        </div>
        
        <div class="order-footer">
          <div class="order-time">
            <p>下单时间: {{ order.createdAt }}</p>
            <p v-if="order.paidAt">支付时间: {{ order.paidAt }}</p>
          </div>
          <div class="order-actions">
            <el-button 
              v-if="order.status === 'PENDING'" 
              type="primary" 
              size="small" 
              @click="handlePay(order.id)">
              立即支付
            </el-button>
            <el-button 
              v-if="order.status === 'PAID' && canRefund(order)" 
              type="warning" 
              size="small" 
              @click="handleRefund(order.id)">
              申请退票
            </el-button>
            <el-button 
              v-if="order.status === 'PENDING'" 
              type="danger" 
              size="small" 
              @click="handleCancel(order.id)">
              取消订单
            </el-button>
            <el-button
              v-if="order.status === 'PAID'"
              type="success"
              size="small"
              @click="viewTicket(order)">
              查看电子票
            </el-button>
          </div>
        </div>
      </el-card>
      
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page.sync="currentPage"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
    
    <!-- 支付对话框 -->
    <el-dialog
      title="订单支付"
      :visible.sync="payDialogVisible"
      width="400px">
      <div class="payment-form">
        <div class="payment-amount">
          <span>支付金额</span>
          <span class="amount">¥{{ currentOrder ? currentOrder.totalAmount : 0 }}</span>
        </div>
        <div class="payment-method">
          <h4>选择支付方式</h4>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="wechat">
              <i class="el-icon-money" style="color: #67C23A"></i> 微信支付
            </el-radio>
            <el-radio label="alipay">
              <i class="el-icon-money" style="color: #409EFF"></i> 支付宝支付
            </el-radio>
          </el-radio-group>
        </div>
        <div class="payment-password">
          <el-form ref="payForm" :model="payForm" :rules="payRules">
            <el-form-item prop="password">
              <el-input 
                type="password" 
                v-model="payForm.password"
                placeholder="请输入支付密码"
                show-password>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment">确认支付</el-button>
      </span>
    </el-dialog>
    
    <!-- 电子票对话框 -->
    <el-dialog
      title="电子票"
      :visible.sync="ticketDialogVisible"
      width="400px"
      center>
      <div class="e-ticket">
        <div class="ticket-header">
          <h3>{{ getMatchName(currentOrder ? currentOrder.matchId : null) }}</h3>
          <p>{{ getMatchTime(currentOrder ? currentOrder.matchId : null) }}</p>
        </div>
        <div class="ticket-venue">
          <p><i class="el-icon-location"></i> {{ getVenueName(currentOrder ? currentOrder.matchId : null) }}</p>
          <p><i class="el-icon-office-building"></i> {{ getSectionName(currentOrder ? currentOrder.sectionId : null) }}</p>
          <p><i class="el-icon-s-custom"></i> 座位号: {{ currentOrder ? currentOrder.ticketNumber : '' }}</p>
        </div>
        <div class="ticket-user">
          <p>姓名: {{ currentOrder ? currentOrder.name : '' }}</p>
          <p>手机: {{ currentOrder ? currentOrder.phone : '' }}</p>
        </div>
        <div class="ticket-qrcode">
          <img :src='require("@/assets/qr.png")' alt="电子票">
        </div>
        <div class="ticket-notice">
          <p>请在比赛开始前30分钟到达场馆</p>
          <p>入场时请出示此电子票</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'OrderList',
  data() {
    return {
      activeTab: 'ALL',
      orders: [],
      matches: {},
      venues: {},
      sections: {},
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      payDialogVisible: false,
      ticketDialogVisible: false,
      currentOrder: null,
      paymentMethod: 'wechat',
      payForm: {
        password: ''
      },
      payRules: {
        password: [
          { required: true, message: '请输入支付密码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    async fetchOrders() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize
        }
        
        if (this.activeTab !== 'ALL') {
          params.status = this.activeTab
        }
        
        const res = await request({
          url: '/api/tickets/orders',
          method: 'get',
          params
        })
        
        this.orders = res.data.records
        this.total = res.data.total
        
        // 获取相关的比赛、场馆和区域信息
        await this.fetchRelatedData()
      } catch (error) {
        console.error('获取订单失败', error)
        this.$message.error('获取订单失败')
      } finally {
        this.loading = false
      }
    },
    async fetchRelatedData() {
      const matchIds = [...new Set(this.orders.map(order => order.matchId))]
      const sectionIds = [...new Set(this.orders.map(order => order.sectionId))]
      
      // 获取比赛信息
      for (const matchId of matchIds) {
        if (!this.matches[matchId]) {
          try {
            const res = await request({
              url: `/api/matches/${matchId}`,
              method: 'get'
            })
            this.matches[matchId] = res.data
            
            // 获取场馆信息
            if (!this.venues[res.data.venueId]) {
              const venueRes = await request({
                url: `/api/venues/${res.data.venueId}`,
                method: 'get'
              })
              this.venues[res.data.venueId] = venueRes.data
            }
          } catch (error) {
            console.error(`获取比赛信息失败: ${matchId}`, error)
          }
        }
      }
      
      // 获取区域信息
      for (const sectionId of sectionIds) {
        if (!this.sections[sectionId]) {
          try {
            const res = await request({
              url: `/api/venue-sections/${sectionId}`,
              method: 'get'
            })
            this.sections[sectionId] = res.data
          } catch (error) {
            console.error(`获取区域信息失败: ${sectionId}`, error)
          }
        }
      }
    },
    handleTabClick() {
      this.currentPage = 1
      this.fetchOrders()
    },
    handlePageChange(page) {
      this.currentPage = page
      this.fetchOrders()
    },
    handlePay(orderId) {
      const order = this.orders.find(o => o.id === orderId)
      if (order) {
        this.currentOrder = order
        this.payDialogVisible = true
      }
    },
    async confirmPayment() {
      if (!this.currentOrder) return
      
      if (this.payForm.password !== '9999') {
        this.$message.error('支付密码错误')
        return
      }
      
      try {
        const res = await request({
          url: `/api/tickets/pay/${this.currentOrder.id}`,
          method: 'post'
        })
        
        if (res.code === 200) {
          this.$message.success('支付成功')
          this.payDialogVisible = false
          this.fetchOrders()
        } else {
          this.$message.error(res.msg || '支付失败')
        }
      } catch (error) {
        console.error('支付订单失败', error)
        this.$message.error('支付订单失败')
      }
    },
    async handleCancel(orderId) {
      try {
        await this.$confirm('确认取消该订单? 取消后无法恢复', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await request({
          url: `/api/tickets/cancel/${orderId}`,
          method: 'post'
        })
        
        if (res.code === 200) {
          this.$message.success('订单已取消')
          this.fetchOrders()
        } else {
          this.$message.error(res.msg || '取消订单失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消订单失败', error)
          this.$message.error('取消订单失败')
        }
      }
    },
    canRefund(order) {
      // 检查比赛是否开始
      const match = this.matches[order.matchId]
      if (!match) return false
      
      const matchTime = new Date(match.matchTime)
      const now = new Date()
      // 比赛24小时前可以退票
      return matchTime.getTime() - now.getTime() > 24 * 60 * 60 * 1000
    },
    async handleRefund(orderId) {
      try {
        await this.$confirm('确认申请退票? 退款将在1-3个工作日内退回支付账户', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await request({
          url: `/api/tickets/refund/${orderId}`,
          method: 'post'
        })
        
        if (res.code === 200) {
          this.$message.success('退票申请已提交')
          this.fetchOrders()
        } else {
          this.$message.error(res.msg || '退票申请失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('退票失败', error)
          this.$message.error('退票失败')
        }
      }
    },
    viewTicket(order) {
      this.currentOrder = order
      this.ticketDialogVisible = true
    },
    getMatchName(matchId) {
      const match = this.matches[matchId]
      if (!match) return '加载中...'
      return `${match.homeTeamName} VS ${match.awayTeamName}`
    },
    getMatchTime(matchId) {
      const match = this.matches[matchId]
      if (!match) return '加载中...'
      // 格式化日期时间
      const date = new Date(match.matchTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    getVenueName(matchId) {
      const match = this.matches[matchId]
      if (!match) return '加载中...'
      return match.venueName || '未知场馆'
    },
    getSectionName(sectionId) {
      const section = this.sections[sectionId]
      return section ? section.name : '加载中...'
    },
    getTeamLogo(matchId, type) {
      const match = this.matches[matchId]
      if (!match) return ''
      return type === 'home' ? match.homeTeamLogo : match.awayTeamLogo
    },
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待支付',
        'PAID': '已支付',
        'CANCELLED': '已取消',
        'REFUNDED': '已退款'
      }
      return statusMap[status] || status
    },
    getStatusClass(status) {
      const classMap = {
        'PENDING': 'status-pending',
        'PAID': 'status-paid',
        'CANCELLED': 'status-cancelled',
        'REFUNDED': 'status-refunded'
      }
      return classMap[status] || ''
    }
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.no-data {
  text-align: center;
  padding: 50px 0;
  color: #909399;
  font-size: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.order-id {
  font-size: 14px;
  color: #606266;
}

.order-status {
  font-weight: bold;
}

.status-pending {
  color: #e6a23c;
}

.status-paid {
  color: #67c23a;
}

.status-cancelled {
  color: #909399;
}

.status-refunded {
  color: #409eff;
}

.order-content {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
}

.match-info {
  flex: 1;
}

.teams {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.team-logo {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.vs {
  margin: 0 20px;
  font-weight: bold;
  color: #606266;
}

.match-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.match-time, .venue-name {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.ticket-info {
  text-align: right;
  min-width: 200px;
}

.section-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.seat-number {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.contact-info {
  margin: 10px 0;
  padding: 10px;
  background: #f8f8f8;
  border-radius: 4px;
}

.contact-info p {
  margin: 5px 0;
  color: #606266;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.contact-info i {
  margin-right: 5px;
  color: #409EFF;
}

.price {
  font-size: 18px;
  color: #ff9800;
  font-weight: bold;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.order-time {
  font-size: 14px;
  color: #909399;
}

.order-time p {
  margin: 5px 0;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 支付对话框样式 */
.payment-form {
  padding: 20px;
}

.payment-amount {
  text-align: center;
  margin-bottom: 20px;
}

.amount {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  margin-left: 10px;
}

.payment-method {
  margin-bottom: 20px;
}

.payment-method h4 {
  margin-bottom: 15px;
}

/* 电子票样式 */
.e-ticket {
  text-align: center;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
}

.ticket-header {
  margin-bottom: 20px;
}

.ticket-header h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.ticket-venue {
  margin-bottom: 20px;
}

.ticket-venue p, .ticket-user p {
  margin: 5px 0;
  color: #606266;
}

.ticket-qrcode {
  margin: 20px 0;
}

.ticket-qrcode img {
  width: 150px;
  height: 150px;
}

.ticket-notice {
  margin-top: 20px;
  font-size: 12px;
  color: #909399;
}
</style>